﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;

namespace Turtle8.MainMenu
{
    class Initialization
    {
        public Initialization()
        {
            setDBServerPath();
            initializeDBTables();
            setBackupPath();
        }

        private void setDBServerPath()
        {
            string s = System.Environment.MachineName;
            modifyInitFile("DBServer", "=", "=" + s + @"\SQLEXPRESS");
        }

        private void setBackupPath()
        {
            //retreiving the path of MSSQL in file system
            string selectStr = CompanyManager.getSqlStringFromFile(@"\other\getInstallationPath.sql");
            SqlCommand selectCmd = new SqlCommand(selectStr, conn);
            SqlDataReader reader = selectCmd.ExecuteReader();
            reader.Read();
            backupPath = (string)reader[0] + @"\Backup";
            reader.Close();

            modifyInitFile("BackupPath", "=", "=" + backupPath);
        }

        private void modifyInitFile(string key, string oldVal, string newVal)
        {
            // create reader & open file
            TextReader tr = new StreamReader(@"other\company.ini");
            TextWriter tw = new StreamWriter(@"other\company-temp.ini");
            string line;

            while ((line = tr.ReadLine()) != null)
            {
                if (line.StartsWith("<" + key))
                    line = line.Replace(oldVal, newVal);
                tw.WriteLine(line);
            }

            tr.Close();
            tw.Close();

            File.Delete(@"other\company.ini");
            File.Move(@"other\company-temp.ini", @"other\company.ini");
            File.Delete(@"other\company-temp.ini");
        }
    }
}
